<template>
  <div>
    <el-row>
      <el-col :span="10">
        <el-button type="primary" size="small" icon="el-icon-caret-left" @click="prev">上一页</el-button>
      </el-col>
      <el-col :span="4" style="font-family:Serif;font-size:40px;font-weight:bold;text-align:center">{{studyInfo.title}}
      </el-col>
    </el-row>
    <el-row style="margin-top:20px">
      <el-col :span="12" :offset="6">
        <el-card v-if="this.studyInfo.row.FILETYPE !='chat'">
          <div id="videoDiv"></div>
        </el-card>
      </el-col>
    </el-row>
    <el-row :gutter="10" class="study-container">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px" class="demo-ruleForm">
        <el-col :span="12" :offset="6">
          <el-form-item label="学习任务序号" prop="TASKSERINO">
            <el-input size="mini" placeholder="请输入案例编号" disabled v-model="ruleForm.TASKSERINO"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="6">
          <el-form-item label="学习开始时间" prop="STUDYBEGINDATE">
            <el-date-picker size="mini" style="width:100%;" v-model="ruleForm.STUDYBEGINDATE" type="date"
              value-format="yyyyMMdd" placeholder="学习开始时间" :picker-options="pickerOptionsStart" @change="changeStart">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="6">
          <el-form-item label="学习结束时间" prop="STUDYENDDATE">
            <el-date-picker style="width:100%;" size="mini" v-model="ruleForm.STUDYENDDATE" type="date"
              value-format="yyyyMMdd" placeholder="学习结束时间" :picker-options="pickerOptionsEnd" @change="changeEnd">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="6">
          <el-form-item label="学习状态" prop="STATUS">
            <!-- <el-select v-model="ruleForm.STATUS" size="mini" filterable clearable placeholder="请选择学习状态">
                <el-option v-for="(item,index) in studyOption" :key="index" :label="item.val" :value="item.code"></el-option>
            </el-select>-->
            <el-input size="mini" placeholder="请输入学习状态" disabled v-model="ruleForm.STATUS"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12" :offset="6">
          <el-form-item>
            <el-button type="primary" size="mini" @click="submitForm('ruleForm')">保存</el-button>
            <el-button @click="resetForm('ruleForm')" size="mini">重置</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
  </div>
</template>

<script>
  import request from "@/common/utils/requestQC";
  import getGlobalParams from "@/common/utils/getGlobalParams";
  import caseStudy from "@/message/QCManage/caseManage/caseStudy";
  import toolBox from "@/common/utils/toolBox";

  export default {
    props: {
      option: Object
    },
    created() {
      this.ruleForm.STUDYBEGINDATE = toolBox.getCurrentMonthFirstDay();
      this.changeStart();
      this.ruleForm.STUDYENDDATE = toolBox.getCurrentMonthLastDay();
      this.changeEnd();
    },
    mounted() {},
    data() {
      return {
        studyInfo: {},
        video_start: 0,
        video_stop: 0,
        videojs: null,
        disabledtime: [],
        recordTimeArr: [],
        videoTimeIndex: 0,
        ruleForm: {
          TASKSERINO: "",
          STUDYBEGINDATE: "",
          STUDYENDDATE: "",
          STATUS: "",
          loading: false
        },
        STATUS: "",
        pickerOptionsStart: {
          disabledDate: time => {
            // return time.getTime() < Date.now()
          }
        },
        pickerOptionsEnd: {
          disabledDate: time => {
            // return time.getTime() < Date.now()
          }
        },
        studyOption: [{
            code: "2",
            val: "已学习"
          },
          {
            code: "1",
            val: "学习中"
          }
        ],
        rules: {
          STUDYBEGINDATE: [{
            required: true,
            message: "请选择学习开始时间",
            trigger: "change"
          }]
          // STUDYENDDATE: [
          //   {
          //     required: true,
          //     message: "请选择学习结束时间",
          //     trigger: "change"
          //   }
          // ],
        }
      };
    },
    created() {
      this.getParams();
    },
    methods: {
      // 返回上一页
      prev() {
        console.log("返回上一页");
        this.$router.go(-1);
      },
      // 接受上一页 table传参，后初始化canvas;
      getParams() {
        // console.log("this.$route.params,", this.$route.params);
        this.studyInfo = this.$route.params;
        this.ruleForm.TASKSERINO = this.studyInfo.row.TASKSERINO;
        this.STATUS = this.studyInfo.row.STATUS;
        this.ruleForm.STATUS =
          this.STATUS == "0" ? "学习中" : this.STATUS == "1" ? "已学习" : "";
        this.openDialog();
      },
      // 指定视频播放开始结束时间
      changestart(time) {
        console.log(this.videojs.currentTime());
        this.video_start = time;
        this.videojs.currentTime(this.video_start);
      },
      addpoint(data) {
        console.log(this.videojs.markers, typeof this.videojs.markers, "1111");
        if (typeof this.videojs.markers === "function") {
          this.videojs.markers();
          this.videojs.markers.add(data);
          this.videojs.markers.updateTime();
          console.log(
            this.videojs.markers.getMarkers(),
            this.videojs.markers,
            "marker"
          );
          var markers = this.videojs.markers.getMarkers();
          for (var i = 0; i < markers.length; i++) {
            if (!markers[i].disabled && i < markers.length - 1) {
              this.disabledtime.push({
                time: [markers[i].time, markers[i + 1].time],
                message: markers[i].message
              });
            } else if (!markers[i].disabled && i == markers.length - 1) {
              this.disabledtime.push({
                time: [markers[i].time, this.video_stop],
                message: markers[i].message
              });
            }
          }
          console.log(this.disabledtime, "gggg");
        }
      },
      // 开启仅能播放的时间段
      setDisabledTime(timeArr) {
        for (var i = 0; i < timeArr.length; i++) {
          if (
            this.videojs.currentTime() >= timeArr[i].time[0] &&
            this.videojs.currentTime() <= timeArr[i].time[1]
          ) {
            this.videojs.pause();
            if (this.recordTimeArr.indexOf(this.videojs.currentTime()) == 0) {
              this.changestart(this.recordTimeArr[1]);
            } else {
              this.changestart(this.recordTimeArr[0]);
            }
            this.$message({
              type: "warning",
              message: timeArr[i].message
            });
          }
        }
      },
      openDialog() {
        console.log(this.studyInfo.row)
        if (this.studyInfo.row.FILETYPE == 'video' || this.studyInfo.row.FILETYPE == 'voice') {
          var url = getGlobalParams.get("FileDownloadAddress")+'/share/'+ this.studyInfo.row.FILEPATH +'/'+ this.studyInfo.row.FILENAME;
          console.log('url',url)
          // var url = "http://192.9.200.48:8012/video-demo/source/badapple.mp4";
          var type = "video/mp4";
          // var url = 'rtmp://58.200.131.2:1935/livetv/hunantv';
          // var type = 'rtmp/flv';
          var that = this;
          var videoElement = document.createElement("video");
          videoElement.id = "videoWindow";
          videoElement.style = "width:100%;" + "height:350px";
          videoElement.className = "video-js vjs-default-skin";
          videoElement.controls = true;
          videoElement.autoplay = true;
          var videoSource = document.createElement("source");
          videoSource.src = url;
          videoSource.type = type;
          videoElement.append(videoSource);
          this.$nextTick(() => {
            document.getElementById("videoDiv").append(videoElement);
            // console.log(
            //   this.$refs,
            //   document.getElementById("videoWindow"),
            //   "lllll"
            // );
            this.videojs = videojs(
              document.getElementById("videoWindow"), {
                controls: true,
                // width: 500,
                // height: 300,
                preload: "auto",
                autoplay: true,
                sources: [
                  //播放的源
                  {
                    src: url,
                    type: type
                  }
                ]
              },
              function () {
                // console.log("video is ready");
                // this.on("loadstart", function () {
                //   console.log("loadstart");
                // });
                this.on("loadedmetadata", function () {
                  // console.log("data has been loade---:", this);
                  that.video_start = 0;
                  that.video_stop = this.duration();
                  var data = [{
                      time: 9,
                      text: "标签1",
                      disabled: true
                    },
                    {
                      time: 40,
                      text: "标签2",
                      disabled: false,
                      message: "标签2不可查看"
                    },
                    {
                      time: 70,
                      text: "标签3",
                      disabled: true
                    },
                    {
                      time: 100,
                      text: "标签4",
                      disabled: false,
                      message: "标签4不可查看"
                    }
                  ];
                  that.addpoint(data);
                });
                this.on("timeupdate", function () {
                  // console.log(this.currentTime());
                  if (this.currentTime() >= that.video_stop) {
                    this.pause();
                  }

                  if (
                    that.videoTimeIndex == 0 &&
                    this.currentTime() !== that.recordTimeArr[1]
                  ) {
                    that.recordTimeArr[that.videoTimeIndex] = this.currentTime();
                    that.videoTimeIndex = 1;
                  } else if (
                    that.videoTimeIndex == 1 &&
                    this.currentTime() !== that.recordTimeArr[0]
                  ) {
                    that.recordTimeArr[that.videoTimeIndex] = this.currentTime();
                    that.videoTimeIndex = 0;
                  }

                  that.setDisabledTime(that.disabledtime);
                });
              }
            );
          });
        }

        this.$forceUpdate();
      },
      //保存
      submitForm(formName) {
        this.$refs[formName].validate(async valid => {
          if (valid) {
            let resBody;
            resBody = new caseStudy();
            resBody.data.TASKSERINO = this.ruleForm.TASKSERINO;
            resBody.data.STUDYBEGINDATE = this.ruleForm.STUDYBEGINDATE;
            resBody.data.STUDYENDDATE = this.ruleForm.STUDYENDDATE;
            if (this.ruleForm.STATUS == '学习中') {
              resBody.data.STATUS = '1';
            } else if (this.ruleForm.STATUS == '已学习') {
              resBody.data.STATUS = '2';
            }

            let response = await request(resBody);
            if (response.SYS_HEAD.ReturnCode == "000000") {
              this.$message({
                type: "success",
                message: "学习进度缓存成功！"
              });
              this.$router.go(-1);
            } else {
              this.$message({
                type: "error",
                message: "请求失败，错误码:" +
                  response.SYS_HEAD.ReturnCode +
                  "，错误信息：" +
                  response.SYS_HEAD.ReturnMessage
              });
            }
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      },
      changeStart() {
        this.pickerOptionsEnd = Object.assign({}, this.pickerOptionsEnd, {
          disabledDate: time => {
            if (this.ruleForm.STUDYBEGINDATE) {
              return (
                time.getTime() <
                Date.parse(
                  this.ruleForm.STUDYBEGINDATE.slice(0, 4) +
                  "-" +
                  this.ruleForm.STUDYBEGINDATE.slice(4, 6) +
                  "-" +
                  this.ruleForm.STUDYBEGINDATE.slice(6, 8)
                ) -
                8.64e7
              );
            } else {
              // return time.getTime() < Date.now();
            }
          }
        });
      },
      changeEnd() {
        this.pickerOptionsStart = Object.assign({}, this.pickerOptionsStart, {
          disabledDate: time => {
            if (this.ruleForm.STUDYENDDATE) {
              return (
                time.getTime() >
                Date.parse(
                  this.ruleForm.STUDYENDDATE.slice(0, 4) +
                  "-" +
                  this.ruleForm.STUDYENDDATE.slice(4, 6) +
                  "-" +
                  this.ruleForm.STUDYENDDATE.slice(6, 8)
                )
              );
            } else {
              // return time.getTime() < Date.now();
            }
          }
        });
      },
      resetForm(formName) {
        if (this.$refs[formName] != undefined) {
          this.$refs[formName].clearValidate();
          this.$refs[formName].resetFields();
        }
      }
    }
  };

</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .study-container {
    margin-top: 60px;
  }

</style>
